<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>编辑食谱 - 健康食谱管理系统</title>
    <link href="https://lib.baomitu.com/twitter-bootstrap/5.2.3/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://lib.baomitu.com/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        .sidebar {
            position: fixed;
            top: 0;
            bottom: 0;
            left: 0;
            z-index: 100;
            padding: 48px 0 0;
            box-shadow: inset -1px 0 0 rgba(0, 0, 0, .1);
            background-color: #f8f9fa;
            width: 250px;
        }
        .sidebar-sticky {
            position: relative;
            top: 0;
            height: calc(100vh - 48px);
            padding-top: .5rem;
            overflow-x: hidden;
            overflow-y: auto;
        }
        .navbar {
            box-shadow: 0 2px 4px rgba(0,0,0,.1);
        }
        main {
            margin-left: 250px;
            padding: 48px 15px 15px;
        }
        .form-container {
            background: white;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0,0,0,.05);
            padding: 1.5rem;
            margin-top: 1rem;
        }
        .nav-link {
            color: #333;
            padding: 0.8rem 1rem;
        }
        .nav-link:hover {
            background-color: #e9ecef;
        }
        .nav-link.active {
            background-color: #007bff;
            color: white;
        }
        .nav-link i {
            width: 20px;
            text-align: center;
            margin-right: 10px;
        }
        .preview-image {
            max-width: 200px;
            max-height: 200px;
            margin-top: 10px;
        }
        .ingredients-list, .steps-list {
            list-style: none;
            padding: 0;
        }
        .ingredients-list li, .steps-list li {
            margin-bottom: 10px;
            display: flex;
            align-items: center;
        }
        .remove-btn {
            margin-left: 10px;
            color: red;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <!-- 顶部导航栏 -->
    <nav class="navbar navbar-dark bg-dark fixed-top">
        <div class="container-fluid">
            <span class="navbar-brand">健康食谱后台管理</span>
            <div class="d-flex">
                <span class="navbar-text me-3" id="adminName"></span>
                <button class="btn btn-outline-light btn-sm" onclick="handleLogout()">退出</button>
            </div>
        </div>
    </nav>

    <!-- 侧边栏 -->
    <nav class="sidebar">
        <div class="sidebar-sticky">
            <ul class="nav flex-column">
                <li class="nav-item">
                    <a class="nav-link" href="index.html">
                        <i class="fas fa-home"></i>仪表盘
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="users.html">
                        <i class="fas fa-users"></i>用户管理
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link active" href="recipes.html">
                        <i class="fas fa-utensils"></i>食谱管理
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="foods.html">
                        <i class="fas fa-apple-alt"></i>食材管理
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="posts.html">
                        <i class="fas fa-comments"></i>帖子管理
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="sports.html">
                        <i class="fas fa-running"></i>运动记录
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="diets.html">
                        <i class="fas fa-hamburger"></i>饮食记录
                    </a>
                </li>
            </ul>
        </div>
    </nav>

    <!-- 主要内容区域 -->
    <main>
        <div class="container-fluid">
            <h1 class="h2 mb-4" id="pageTitle">编辑食谱</h1>
            
            <div class="form-container">
                <form id="recipeForm">
                    <!-- 基本信息 -->
                    <div class="mb-4">
                        <h3>基本信息</h3>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">食谱名称</label>
                                <input type="text" class="form-control" id="name" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">分类</label>
                                <input type="text" class="form-control" id="category">
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">描述</label>
                            <textarea class="form-control" id="description" rows="3" required></textarea>
                        </div>
                    </div>

                    <!-- 食材和步骤 -->
                    <div class="mb-4">
                        <h3>食材和步骤</h3>
                        <div class="row">
                            <div class="col-md-6">
                                <label class="form-label">食材</label>
                                <div class="input-group mb-2">
                                    <input type="text" class="form-control" id="ingredientInput">
                                    <button type="button" class="btn btn-primary" onclick="addIngredient()">添加</button>
                                </div>
                                <ul class="ingredients-list" id="ingredientsList"></ul>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">步骤</label>
                                <div class="input-group mb-2">
                                    <input type="text" class="form-control" id="stepInput">
                                    <button type="button" class="btn btn-primary" onclick="addStep()">添加</button>
                                </div>
                                <ul class="steps-list" id="stepsList"></ul>
                            </div>
                        </div>
                    </div>

                    <!-- 其他信息 -->
                    <div class="mb-4">
                        <h3>其他信息</h3>
                        <div class="row">
                            <div class="col-md-4 mb-3">
                                <label class="form-label">烹饪时间（分钟）</label>
                                <input type="number" class="form-control" id="cookingTime" required>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label">难度</label>
                                <select class="form-select" id="difficulty" required>
                                    <option value="简单">简单</option>
                                    <option value="中等">中等</option>
                                    <option value="困难">困难</option>
                                </select>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label">图片</label>
                                <input type="file" class="form-control" id="image" accept="image/*">
                                <input type="hidden" id="imageUrl">
                                <img id="imagePreview" class="preview-image" style="display: none;">
                            </div>
                        </div>
                    </div>

                    <!-- 营养信息 -->
                    <div class="mb-4">
                        <h3>营养信息</h3>
                        <div class="row">
                            <div class="col-md-3 mb-3">
                                <label class="form-label">热量（千卡）</label>
                                <input type="number" class="form-control" id="calories">
                            </div>
                            <div class="col-md-3 mb-3">
                                <label class="form-label">蛋白质（克）</label>
                                <input type="number" class="form-control" id="protein">
                            </div>
                            <div class="col-md-3 mb-3">
                                <label class="form-label">碳水化合物（克）</label>
                                <input type="number" class="form-control" id="carbs">
                            </div>
                            <div class="col-md-3 mb-3">
                                <label class="form-label">脂肪（克）</label>
                                <input type="number" class="form-control" id="fat">
                            </div>
                        </div>
                    </div>

                    <!-- 标签 -->
                    <div class="mb-4">
                        <h3>标签</h3>
                        <div class="input-group mb-3">
                            <input type="text" class="form-control" id="tagInput" placeholder="输入标签后按回车添加">
                            <button type="button" class="btn btn-primary" onclick="addTag()">添加</button>
                        </div>
                        <div id="tagsList" class="d-flex flex-wrap gap-2"></div>
                    </div>

                    <!-- 提交按钮 -->
                    <div class="text-center">
                        <button type="submit" class="btn btn-primary">保存</button>
                        <button type="button" class="btn btn-secondary ms-2" onclick="history.back()">返回</button>
                    </div>
                </form>
            </div>
        </div>
    </main>

    <script src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://lib.baomitu.com/twitter-bootstrap/5.2.3/js/bootstrap.bundle.min.js"></script>
    <script>
        let recipeId = null;
        let ingredients = [];
        let steps = [];
        let tags = [];

        // 页面加载完成后执行
        document.addEventListener('DOMContentLoaded', function() {
            showAdminName();
            
            // 获取URL参数中的recipeId
            const urlParams = new URLSearchParams(window.location.search);
            recipeId = urlParams.get('id');
            
            if (recipeId) {
                document.getElementById('pageTitle').textContent = '编辑食谱';
                loadRecipeData(recipeId);
            } else {
                document.getElementById('pageTitle').textContent = '新增食谱';
            }

            // 表单提交事件
            document.getElementById('recipeForm').addEventListener('submit', handleSubmit);
            
            // 图片预览
            document.getElementById('image').addEventListener('change', handleImagePreview);
            
            // 标签输入框回车事件
            document.getElementById('tagInput').addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    e.preventDefault();
                    addTag();
                }
            });
        });

        // 显示管理员名称
        function showAdminName() {
            try {
                const adminUser = JSON.parse(localStorage.getItem('adminUser') || '{}');
                document.getElementById('adminName').textContent = adminUser.nickname || adminUser.username || '';
            } catch (error) {
                console.error('显示管理员名称失败:', error);
            }
        }

        // 处理退出登录
        function handleLogout() {
            localStorage.removeItem('adminToken');
            localStorage.removeItem('adminUser');
            window.location.href = '/admin/login.html';
        }

        // 加载食谱数据
        async function loadRecipeData(id) {
            try {
                const token = localStorage.getItem('adminToken');
                if (!token) {
                    window.location.href = '/admin/login.html';
                    return;
                }

                const response = await fetch(`/api/admin/recipes/${id}`, {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });

                if (!response.ok) {
                    throw new Error('加载食谱数据失败');
                }

                const result = await response.json();
                if (result.code === 0) {
                    const recipe = result.data;
                    
                    // 填充表单数据
                    document.getElementById('name').value = recipe.name;
                    document.getElementById('category').value = recipe.category;
                    document.getElementById('description').value = recipe.description;
                    document.getElementById('cookingTime').value = recipe.cookingTime;
                    document.getElementById('difficulty').value = recipe.difficulty;
                    
                    // 设置食材和步骤
                    ingredients = recipe.ingredients || [];
                    steps = recipe.steps || [];
                    renderIngredients();
                    renderSteps();
                    
                    // 设置营养信息
                    if (recipe.nutrition) {
                        document.getElementById('calories').value = recipe.nutrition.calories;
                        document.getElementById('protein').value = recipe.nutrition.protein;
                        document.getElementById('carbs').value = recipe.nutrition.carbs;
                        document.getElementById('fat').value = recipe.nutrition.fat;
                    }
                    
                    // 设置标签
                    tags = recipe.tags || [];
                    renderTags();
                    
                    // 显示图片预览
                    if (recipe.image) {
                        document.getElementById('imagePreview').src = recipe.image;
                        document.getElementById('imagePreview').style.display = 'block';
                    }
                }
            } catch (error) {
                console.error('加载食谱数据失败:', error);
                alert('加载食谱数据失败');
            }
        }

        // 处理图片预览
        async function handleImagePreview(e) {
            const file = e.target.files[0];
            if (file) {
                try {
                    // 显示加载中
                    const loadingEl = document.createElement('div');
                    loadingEl.id = 'loading-overlay';
                    loadingEl.innerHTML = `
                        <div class="loading-spinner">
                            <div class="spinner-border text-primary" role="status">
                                <span class="visually-hidden">上传中...</span>
                            </div>
                            <div class="mt-2">上传中...</div>
                        </div>
                    `;
                    document.body.appendChild(loadingEl);

                    // 立即上传图片
                    const token = localStorage.getItem('adminToken');
                    if (!token) {
                        throw new Error('请先登录');
                    }

                    const formData = new FormData();
                    formData.append('file', file);

                    const uploadResponse = await fetch('/api/upload', {
                        method: 'POST',
                        headers: {
                            'Authorization': `Bearer ${token}`
                        },
                        body: formData
                    });

                    if (!uploadResponse.ok) {
                        throw new Error('上传图片失败');
                    }

                    const uploadResult = await uploadResponse.json();
                    if (uploadResult.code === 0 && uploadResult.data && uploadResult.data.url) {
                        // 更新预览图片和保存图片URL
                        document.getElementById('imagePreview').src = uploadResult.data.url;
                        document.getElementById('imagePreview').style.display = 'block';
                        document.getElementById('imageUrl').value = uploadResult.data.url;
                        alert('上传成功');
                    } else {
                        throw new Error(uploadResult.message || '上传失败');
                    }
                } catch (error) {
                    console.error('上传图片失败:', error);
                    alert(error.message || '上传失败');
                } finally {
                    // 移除loading效果
                    const loadingEl = document.getElementById('loading-overlay');
                    if (loadingEl) {
                        loadingEl.remove();
                    }
                }
            }
        }

        // 添加食材
        function addIngredient() {
            const input = document.getElementById('ingredientInput');
            const value = input.value.trim();
            if (value) {
                ingredients.push(value);
                input.value = '';
                renderIngredients();
            }
        }

        // 渲染食材列表
        function renderIngredients() {
            const list = document.getElementById('ingredientsList');
            list.innerHTML = ingredients.map((item, index) => `
                <li>
                    ${item}
                    <span class="remove-btn" onclick="removeIngredient(${index})">×</span>
                </li>
            `).join('');
        }

        // 删除食材
        function removeIngredient(index) {
            ingredients.splice(index, 1);
            renderIngredients();
        }

        // 添加步骤
        function addStep() {
            const input = document.getElementById('stepInput');
            const value = input.value.trim();
            if (value) {
                steps.push(value);
                input.value = '';
                renderSteps();
            }
        }

        // 渲染步骤列表
        function renderSteps() {
            const list = document.getElementById('stepsList');
            list.innerHTML = steps.map((item, index) => `
                <li>
                    ${index + 1}. ${item}
                    <span class="remove-btn" onclick="removeStep(${index})">×</span>
                </li>
            `).join('');
        }

        // 删除步骤
        function removeStep(index) {
            steps.splice(index, 1);
            renderSteps();
        }

        // 添加标签
        function addTag() {
            const input = document.getElementById('tagInput');
            const value = input.value.trim();
            if (value && !tags.includes(value)) {
                tags.push(value);
                input.value = '';
                renderTags();
            }
        }

        // 渲染标签
        function renderTags() {
            const container = document.getElementById('tagsList');
            container.innerHTML = tags.map((tag, index) => `
                <span class="badge bg-primary">
                    ${tag}
                    <span class="ms-2" style="cursor: pointer;" onclick="removeTag(${index})">×</span>
                </span>
            `).join('');
        }

        // 删除标签
        function removeTag(index) {
            tags.splice(index, 1);
            renderTags();
        }

        // 处理表单提交
        async function handleSubmit(e) {
            e.preventDefault();
            
            try {
                const token = localStorage.getItem('adminToken');
                if (!token) {
                    window.location.href = '/admin/login.html';
                    return;
                }

                // 构建请求数据
                const recipeData = {
                    name: document.getElementById('name').value,
                    category: document.getElementById('category').value,
                    description: document.getElementById('description').value,
                    cookingTime: parseInt(document.getElementById('cookingTime').value),
                    difficulty: document.getElementById('difficulty').value,
                    ingredients,
                    steps,
                    image: document.getElementById('imageUrl').value, // 使用已上传的图片URL
                    nutrition: {
                        calories: parseFloat(document.getElementById('calories').value) || 0,
                        protein: parseFloat(document.getElementById('protein').value) || 0,
                        carbs: parseFloat(document.getElementById('carbs').value) || 0,
                        fat: parseFloat(document.getElementById('fat').value) || 0
                    },
                    tags
                };

                // 发送请求
                const url = recipeId ? 
                    `/api/admin/recipes/${recipeId}` : 
                    '/api/admin/recipes';
                    
                const response = await fetch(url, {
                    method: recipeId ? 'PUT' : 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    },
                    body: JSON.stringify(recipeData)
                });

                if (!response.ok) {
                    throw new Error('保存食谱失败');
                }

                const result = await response.json();
                if (result.code === 0) {
                    alert('保存成功');
                    window.location.href = '/admin/recipes.html';
                } else {
                    throw new Error(result.message || '保存食谱失败');
                }
            } catch (error) {
                console.error('保存食谱失败:', error);
                alert(error.message || '保存失败，请重试');
            }
        }
    </script>
</body>
</html> 